package in.abip.chisame;

import java.util.List;

import in.abip.chisame.model.Hvac;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

/**
 * HVAC activity.
 * 
 * @author Julot.
 * @since Thursday, January 26th, 2011.
 */
public class HvacListActivity extends NetworkActivity {
	Adapter _adapter = null;
	
	/**
	 * Adapter for HVAC list view.
	 * 
	 * @author Julot.
	 * @since Thursday, January 27, 2011.
	 */
	private class Adapter extends ListAdapter {
		public Adapter(Context context, int viewResourceId,
				List<Object> objects) {
			super(context, viewResourceId, objects);
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			
			Button down = (Button) view.findViewById(R.id.down);
			down.setOnClickListener(_downClickListener);
			Hvac item = (Hvac) _objects.get(position);
			down.setTag(item);
			
			Button up = (Button) view.findViewById(R.id.up);
			up.setOnClickListener(_upClickListener);
			up.setTag(item);
			
			return view;
		}
	}
	
	/**
	 * Listener for down click.
	 */
	OnClickListener _downClickListener = new OnClickListener() {
		public void onClick(View view) {
			Hvac hvac = (Hvac) view.getTag();
			send(hvac.getRunCmd(100));
		}
	};
	
	/**
	 * Listener for up click.
	 */
	OnClickListener _upClickListener = new OnClickListener() {
		public void onClick(View view) {
			Hvac hvac = (Hvac) view.getTag();
			send(hvac.getRunCmd(0));
		}
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_activity);
        populate();
    }
    
	/** Populate list view. */
	protected void populate() {
        _adapter = new Adapter(
    		this,
    		R.layout.list_item_updown,
    		loadHvacs()
		);
        ListView view = (ListView) findViewById(R.id.list);
        view.setAdapter(_adapter);
	}
	
	private List<Object> loadHvacs() {
		Bundle bundle = getIntent().getExtras();
		List<Object> hvacs = null;
		if (bundle != null) {
			hvacs = Hvac.model().findAll(
				"roomId = " + bundle.getInt("roomId")
			);
		}
		else hvacs = Hvac.model().findAll();
		return hvacs;
	}
    
	/**
	 * Refresh list with current status from server.
	 */
	protected void refresh() {
		String command;
		for (Object item : _adapter.getItems()) {
			Hvac model = (Hvac) item;
			command = model.getAskCmd();
			udpOutputs.add(command);
			tcpOutputs.add(command);
		}
		startSend();
	}
	
}
